/**
 * 轻量级的跨平台EventEmitter实现
 * 兼容所有现代浏览器和移动设备
 * 
 * 兼容性：
 * - 桌面浏览器：Chrome 14+, Firefox 16+, Safari 5.1+, Edge所有版本
 * - 移动浏览器：iOS Safari 5+, Chrome Mobile所有版本, Android 4+
 * - 小程序：微信、支付宝、百度等所有小程序环境
 */

export interface EventListener {
  (...args: any[]): void;
}

export class EventEmitter {
  // 使用对象而不是Map，确保最大兼容性
  private events: { [key: string]: EventListener[] } = {};
  private maxListeners: number = 10;

  /**
   * 设置最大监听器数量
   */
  setMaxListeners(n: number): this {
    this.maxListeners = n;
    return this;
  }

  /**
   * 添加事件监听器
   */
  on(event: string, listener: EventListener): this {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    
    const listeners = this.events[event];
    
    // 警告可能的内存泄漏
    if (listeners.length >= this.maxListeners) {
      if (typeof console !== 'undefined' && console.warn) {
        console.warn(
          `Warning: Possible EventEmitter memory leak detected. ` +
          `${listeners.length} ${event} listeners added. ` +
          `Use emitter.setMaxListeners() to increase limit`
        );
      }
    }
    
    listeners.push(listener);
    return this;
  }

  /**
   * 添加事件监听器（on的别名）
   */
  addListener(event: string, listener: EventListener): this {
    return this.on(event, listener);
  }

  /**
   * 添加一次性事件监听器
   */
  once(event: string, listener: EventListener): this {
    const onceWrapper = (...args: any[]) => {
      this.off(event, onceWrapper);
      listener.apply(this, args);
    };
    // 保留原始监听器引用，用于removeListener
    (onceWrapper as any).listener = listener;
    return this.on(event, onceWrapper);
  }

  /**
   * 移除事件监听器
   */
  off(event: string, listener: EventListener): this {
    const listeners = this.events[event];
    
    if (!listeners) {
      return this;
    }
    
    // 查找并移除监听器
    for (let i = listeners.length - 1; i >= 0; i--) {
      const l = listeners[i];
      if (l === listener || (l as any).listener === listener) {
        listeners.splice(i, 1);
        break;
      }
    }
    
    // 如果没有监听器了，删除事件键
    if (listeners.length === 0) {
      delete this.events[event];
    }
    
    return this;
  }

  /**
   * 移除事件监听器（off的别名）
   */
  removeListener(event: string, listener: EventListener): this {
    return this.off(event, listener);
  }

  /**
   * 移除所有监听器
   */
  removeAllListeners(event?: string): this {
    if (event) {
      delete this.events[event];
    } else {
      this.events = {};
    }
    return this;
  }

  /**
   * 触发事件
   */
  emit(event: string, ...args: any[]): boolean {
    const listeners = this.events[event];
    
    if (!listeners || listeners.length === 0) {
      return false;
    }
    
    // 创建监听器数组的副本，避免在执行过程中被修改
    const listenersCopy = listeners.slice();
    
    for (let i = 0; i < listenersCopy.length; i++) {
      const listener = listenersCopy[i];
      try {
        listener.apply(this, args);
      } catch (error) {
        // 错误处理，防止一个监听器的错误影响其他监听器
        if (typeof console !== 'undefined' && console.error) {
          console.error(`Error in event listener for '${event}':`, error);
        }
      }
    }
    
    return true;
  }

  /**
   * 获取事件的监听器数量
   */
  listenerCount(event: string): number {
    const listeners = this.events[event];
    return listeners ? listeners.length : 0;
  }

  /**
   * 获取事件的所有监听器
   */
  listeners(event: string): EventListener[] {
    return this.events[event] ? [...this.events[event]] : [];
  }

  /**
   * 获取所有事件名称
   */
  eventNames(): string[] {
    return Object.keys(this.events);
  }

  /**
   * 预置事件（用于提前分配内存，提高性能）
   */
  prependListener(event: string, listener: EventListener): this {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].unshift(listener);
    return this;
  }

  /**
   * 预置一次性监听器
   */
  prependOnceListener(event: string, listener: EventListener): this {
    const onceWrapper = (...args: any[]) => {
      this.off(event, onceWrapper);
      listener.apply(this, args);
    };
    (onceWrapper as any).listener = listener;
    return this.prependListener(event, onceWrapper);
  }
}

// 导出默认实例工厂
export function createEventEmitter(): EventEmitter {
  return new EventEmitter();
}

// 兼容CommonJS
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { EventEmitter, createEventEmitter };
}

export default EventEmitter;